/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConnectInfoDialog.java
 *
 * Created on Jun 3, 2012, 11:15:55 PM
 */
package gui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author HoangLiem
 */
public class ConnectInfoDialog extends javax.swing.JDialog {

    private String serverHost;
    private Integer port;
    private String userName;
    private String passWord;
    private boolean cancelClicked;
    private Socket socket;
    private ArrayList<String> databaseNames;

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getServerHost() {
        return serverHost;
    }

    public void setServerHost(String serverHost) {
        this.serverHost = serverHost;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public boolean isCancelClicked() {
        return cancelClicked;
    }

    public void setCancelClicked(boolean cancelClicked) {
        this.cancelClicked = cancelClicked;
    }

    public ArrayList<String> getDatabaseNames() {
        return databaseNames;
    }

    public void setDatabaseNames(ArrayList<String> databaseNames) {
        this.databaseNames = databaseNames;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    /** Creates new form ConnectInfoDialog */
    public ConnectInfoDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jtfServerHost = new javax.swing.JTextField();
        jtfPort = new javax.swing.JTextField();
        jtfUserName = new javax.swing.JTextField();
        jbtConnect = new javax.swing.JButton();
        jbtCancel = new javax.swing.JButton();
        jpfPassWord = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Connect to server");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Server host :");

        jLabel2.setText("Port :");

        jLabel3.setText("Username :");

        jLabel4.setText("Password :");

        jtfServerHost.setText("localhost");
        jtfServerHost.setToolTipText("");

        jtfPort.setText("5000");

        jtfUserName.setText("root");

        jbtConnect.setText("Connect");
        jbtConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtConnectActionPerformed(evt);
            }
        });

        jbtCancel.setText("Cancel");
        jbtCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbtConnect)
                        .addGap(32, 32, 32)
                        .addComponent(jbtCancel))
                    .addComponent(jtfServerHost, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                    .addComponent(jtfPort)
                    .addComponent(jtfUserName)
                    .addComponent(jpfPassWord))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfServerHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jpfPassWord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtConnect)
                    .addComponent(jbtCancel))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCancelActionPerformed
        // TODO add your handling code here:
        cancelClicked = true;
        this.dispose();
    }//GEN-LAST:event_jbtCancelActionPerformed

    public static boolean isNumberAll(String str) {
        boolean result = true;
        if (str == null || str.equals("")) {
            return result = false;
        }
        try {
            Pattern pattern = Pattern.compile("\\d*");
            Matcher matcher = pattern.matcher(str);
            if (!matcher.matches()) {
                result = false;
            }
        } catch (Exception ex) {
            result = false;
            ex.printStackTrace();
        }
        return result;
    }

    public static boolean isInteger(String str) {
        boolean result = true;
        result = isNumberAll(str);
        return result;
    }

    private void jbtConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtConnectActionPerformed
        // TODO add your handling code here:

        String serverHost = "";
        String port = "";
        String userName = "";
        String passWord = "";

        serverHost = jtfServerHost.getText().trim();
        port = jtfPort.getText().trim();
        userName = jtfUserName.getText().trim();
        passWord = String.copyValueOf(jpfPassWord.getPassword());
        if (serverHost.equals("")) {
            JOptionPane.showMessageDialog(this, "Server host must be not empty");
            return;
        }
        if (port.equals("")) {
            JOptionPane.showMessageDialog(this, "Port must be not empty");
            return;
        } else {
            if (!isInteger(port)) {
                JOptionPane.showMessageDialog(this, "Port must be integer");
                return;
            }
        }
        if (userName.equals("")) {
            JOptionPane.showMessageDialog(this, "Username must be not empty");
            return;
        }
        //neu thoa het, thi set gia tri cac thuoc tinh
        this.setServerHost(serverHost);
        this.setPort(Integer.parseInt(port));
        this.setUserName(userName);
        this.setPassWord(passWord);

        try {
            socket = new Socket(this.getServerHost(), this.getPort());
            //gui username, password
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write(this.getUserName());
            bw.newLine();
            bw.flush();
            bw.write(this.getPassWord());
            bw.newLine();
            bw.flush();
            //lay thong tin show len
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String info = br.readLine();
            if (info.equalsIgnoreCase("connected")) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                databaseNames = (ArrayList<String>) ois.readObject();
                bw.write("query");
                bw.newLine();
                bw.flush();
                this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(this, "Connect fail");
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectInfoDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtConnectActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        cancelClicked = false;
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        cancelClicked = true;
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConnectInfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConnectInfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConnectInfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConnectInfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ConnectInfoDialog dialog = new ConnectInfoDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JButton jbtCancel;
    private javax.swing.JButton jbtConnect;
    private javax.swing.JPasswordField jpfPassWord;
    private javax.swing.JTextField jtfPort;
    private javax.swing.JTextField jtfServerHost;
    private javax.swing.JTextField jtfUserName;
    // End of variables declaration//GEN-END:variables
}
